#include <iostream>
#include <atomic>
#include <thread>
#include <chrono>
#include "SCAllocator.hpp"

const int iterations = 100;                // 每个线程的迭代次数
const int maxBlockSize = 16 * 1024 * 1024; // 64MB，最大申请大小
const int numThreads = 8;                 // 线程数

class buffer {
public:
    buffer(int64_t ID) : id(ID) {}
    int64_t id;
    char buf[1024];
};

void threadFunction(int threadId, std::atomic<int>& count) {
    std::srand(std::time(nullptr) + threadId);  // 每个线程设置不同的随机种子
    std::chrono::duration<double> allocTime(0);
    std::chrono::duration<double> deallocTime(0);

    buffer* bufs[iterations];
    void* ptrs[iterations];

    auto startAlloc = std::chrono::high_resolution_clock::now();
    for (int i = 0; i < iterations; ++i) {
        int size = (std::rand() % maxBlockSize) + 1;  // 随机生成1到maxBlockSize之间的大小
        bufs[i] = SC::allocateMemory<buffer>(count);  // 分配内存
        ptrs[i] = SC::allocateMemory(size);
    }
    auto endAlloc = std::chrono::high_resolution_clock::now();
    allocTime += endAlloc - startAlloc;

    auto startDealloc = std::chrono::high_resolution_clock::now();
    for (int i = 0; i < iterations; ++i) {
        SC::deallocateMemory(bufs[i]);
        SC::deallocateMemory(ptrs[i]);
    }
    auto endDealloc = std::chrono::high_resolution_clock::now();
    deallocTime += endDealloc - startDealloc;

    count += iterations;

    // 打印每个线程的分配和释放时间
    std::cout << "线程 " << threadId << " 分配时间: " << allocTime.count() << " 秒, 释放时间: " << deallocTime.count() << " 秒" << std::endl;
}

int main() {
    std::atomic<int> count(0);

    std::thread threads[numThreads];
    std::chrono::duration<double> totalTime(0);

    auto startTotal = std::chrono::high_resolution_clock::now();
    for (int i = 0; i < numThreads; ++i) {
        threads[i] = std::thread(threadFunction, i, std::ref(count));
    }

    for (int i = 0; i < numThreads; ++i) {
        threads[i].join();
    }
    auto endTotal = std::chrono::high_resolution_clock::now();
    totalTime = endTotal - startTotal;

    std::cout << numThreads << " 个线程,每个线程执行最大随机 " << maxBlockSize/(1024*1024) << "MB " << iterations << " 次 "<< std::endl;
    std::cout << "总执行时间: " << totalTime.count() << " 秒" << std::endl;

    return 0;
}
